package com.example.rbac.controller;

import com.example.rbac.annotation.RequirePermission;
import com.example.rbac.common.Result;
import com.example.rbac.model.Role;
import com.example.rbac.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/role")
@Api(tags = "角色管理")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    @GetMapping("/list")
    @ApiOperation("获取角色列表")
    @RequirePermission(value = "role:list", name = "查看角色列表")
    public Result<?> getRoleList(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String roleName) {
        Page<Role> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (roleName != null && !roleName.isEmpty()) {
            queryWrapper.like("role_name", roleName);
        }
        Page<Role> rolePage = roleService.page(page, queryWrapper);
        return Result.success(rolePage);
    }
    
    @GetMapping("/{id}")
    @ApiOperation("获取角色详情")
    @RequirePermission(value = "role:info", name = "查看角色详情")
    public Result<?> getRoleById(@PathVariable Long id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        return Result.success(role);
    }
    
    @PostMapping
    @ApiOperation("新增角色")
    @RequirePermission(value = "role:add", name = "新增角色")
    public Result<?> addRole(@RequestBody Role role) {
        roleService.save(role);
        return Result.success("添加成功");
    }
    
    @PutMapping
    @ApiOperation("修改角色")
    @RequirePermission(value = "role:edit", name = "修改角色")
    public Result<?> updateRole(@RequestBody Role role) {
        roleService.updateById(role);
        return Result.success("修改成功");
    }
    
    @DeleteMapping("/{id}")
    @ApiOperation("删除角色")
    @RequirePermission(value = "role:delete", name = "删除角色")
    public Result<?> deleteRole(@PathVariable Long id) {
        roleService.removeById(id);
        return Result.success("删除成功");
    }
    
    @PostMapping("/assign")
    @ApiOperation("给用户分配角色")
    @RequirePermission(value = "role:assign", name = "分配角色")
    public Result<?> assignRoles(@RequestBody Map<String, Object> params) {
        Long userId = Long.parseLong(params.get("userId").toString());
        List<Long> roleIds = (List<Long>) params.get("roleIds");
        roleService.assignRolesToUser(userId, roleIds);
        return Result.success("角色分配成功");
    }
}